/*
' DotNetNuke?- http://www.dotnetnuke.com
' Copyright (c) 2002-2006
' by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Data;
using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.IO;


namespace M2Land.Modules.FlashImageRotator
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditFlashImageRotator class is used to manage content
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// </history>
    /// -----------------------------------------------------------------------------
    partial class EditFlashImageRotator : PortalModuleBase
    {

        #region Private Members

        private int ItemId = Null.NullInteger;
        private bool _isNew = true;
        private string strImageXMLFilePath = Null.NullString;
        private string strImageXMLFilePathInServer = Null.NullString;
        private string strImageXMLFolderPath = Null.NullString;
        private string strImageXMLFolderPathInServer = Null.NullString;
        private string AudioFileTypes = "WAVE,MP3";
        private string ImageFileTypes = "JPEG,JPE,JPG,BMP,PNG,GIF";

        #endregion

        #region Event Handlers

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                //Initial the XML image file list path
                strImageXMLFilePath = ModulePath + "Flash/ImageList.xml";
                strImageXMLFilePathInServer = Server.MapPath(strImageXMLFilePath);

                strImageXMLFolderPath = ModulePath + "Flash/";
                strImageXMLFolderPathInServer = Server.MapPath(strImageXMLFolderPath);


                //Get the IsNew state from the ViewState
                _isNew = Convert.ToBoolean(ViewState["IsNew"]);

                

                if (Page.IsPostBack == false)
                {
                    urlctlLogo.FileFilter = ImageFileTypes;
                    urlctlAudio.FileFilter = AudioFileTypes;

                    InitImgXMLListDropDownList();
                    BindConfig();
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }



        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                FlashImageRotatorController objFlashImageRotatorController = new FlashImageRotatorController();
                FlashImageRotatorInfo objFlashImageRotatorInfo = new FlashImageRotatorInfo();
                objFlashImageRotatorInfo = new FlashImageRotatorInfo();

                //The Basics:
                objFlashImageRotatorInfo.ModuleID = ModuleId;

                if (txtHeight.Text.Trim() != String.Empty)
                {
                    objFlashImageRotatorInfo.Height = int.Parse(txtHeight.Text);
                }

                if (txtWidth.Text.Trim() != String.Empty)
                {
                    objFlashImageRotatorInfo.Width = int.Parse(txtWidth.Text);
                }
                objFlashImageRotatorInfo.File = ddlImageListXMLFile.SelectedValue.ToString().Trim();
                objFlashImageRotatorInfo.Transtion = droplistTranstion.SelectedValue;

                //The Colors:
                objFlashImageRotatorInfo.BackColor = cpicBackColor.Color;
                objFlashImageRotatorInfo.FrontColor = cpicFrontColor.Color;
                objFlashImageRotatorInfo.LightColor = cpicLightColor.Color;
                objFlashImageRotatorInfo.ScreenColor = cpicScreenColor.Color;

                //Display Appearance:
                objFlashImageRotatorInfo.Logo = urlctlLogo.Url;
                objFlashImageRotatorInfo.OverStrech = droplistOverStretch.SelectedValue;
                objFlashImageRotatorInfo.ShowIcons = Boolean.Parse(droplistShowIcon.SelectedValue);
                objFlashImageRotatorInfo.ShowEq = Boolean.Parse(droplistShowEq.SelectedValue);

                //Controlbar Appearance:
                objFlashImageRotatorInfo.ShowNavigation = Boolean.Parse(droplistShowNavigation.SelectedValue);

                //Playback Behaviour:
                objFlashImageRotatorInfo.Audio = urlctlAudio.Url;
                objFlashImageRotatorInfo.AutoStart = Boolean.Parse(droplistAutoStart.SelectedValue);
                objFlashImageRotatorInfo.Repeat = droplistRepeat.SelectedValue;
                if (txtRotateTime.Text.Trim() != String.Empty)
                {
                    objFlashImageRotatorInfo.RotateTime = Int32.Parse(txtRotateTime.Text);
                }
                objFlashImageRotatorInfo.Shuffle = Boolean.Parse(droplistShuffle.SelectedValue);
                if (txtVolume.Text.Trim() != String.Empty)
                {
                    objFlashImageRotatorInfo.Volume = Int32.Parse(txtVolume.Text);
                }

                //External Commnunication:
                objFlashImageRotatorInfo.EnableJS = Boolean.Parse(droplistEnableJs.SelectedValue);
                objFlashImageRotatorInfo.JavascriptID = txtJavascriptID.Text;
                objFlashImageRotatorInfo.LinkFromDisplay = Boolean.Parse(droplistLinkFromDisplay.SelectedValue);
                objFlashImageRotatorInfo.LinkTarget = txtLinkTarget.Text;


                if (_isNew)
                {
                    objFlashImageRotatorController.AddFlashImageRotator(objFlashImageRotatorInfo);

                }
                else
                {
                    objFlashImageRotatorController.UpdateFlashImageRotator(objFlashImageRotatorInfo);

                }




                //Write XML image list file file
                strImageXMLFilePathInServer = Null.NullString;
                strImageXMLFilePathInServer = strImageXMLFolderPathInServer + ddlImageListXMLFile.SelectedValue.ToString();

                //Reset XML image list file attributes
                if (File.Exists(strImageXMLFilePathInServer))
                {
                    File.SetAttributes(strImageXMLFilePathInServer, FileAttributes.Normal);
                }

                StreamWriter objStream = File.CreateText(strImageXMLFilePathInServer);
                objStream.WriteLine(txtImageListXML.Text);
                objStream.Close();


                //refresh cache

                //********************************************************************//
                //ModuleController.SynchronizeModule(Int32) 
                //function is not supported by DNN 4.5.5, try to solve this problem, but
                //the follow code doesn't work, so remark it at first and keep up 
                //ModuleController.SynchronizeModule(ModuleId); funtion. Because using 
                //this function, this version doesn't support DNN 4.5.5 and below!
                //********************************************************************//


                //Version CurrentDNNVersion = new Version(Globals.glbAppVersion);
                //Version TargetDNNVersion = new Version("04.06.00");
                //if (CurrentDNNVersion > TargetDNNVersion)
                //{
                //    ModuleController.SynchronizeModule(ModuleId);
                //}

                ModuleController.SynchronizeModule(ModuleId);

                //Redirect back to the portal home page
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }

        }

        protected void ddlImageListXMLFile_SelectedIndexChanged(object sender, EventArgs e)
        {
            strImageXMLFilePathInServer = Null.NullString;
            strImageXMLFilePathInServer = strImageXMLFolderPathInServer + ddlImageListXMLFile.SelectedValue.ToString();

            txtImageListXML.Text = LoadImgeListXMLFile(strImageXMLFilePathInServer);
        }

        #endregion

        #region Help functions
        private void InitImgXMLListDropDownList()
        {
            //Initate Image XML list dropdownlist
            DirectoryInfo Dir = new DirectoryInfo(strImageXMLFolderPathInServer);

            FileInfo[] FileList = Dir.GetFiles("*.xml", SearchOption.TopDirectoryOnly);

            ddlImageListXMLFile.DataSource = FileList;

            ddlImageListXMLFile.DataBind();
        }

        private string LoadImgeListXMLFile(string ImageXMLFilePathInServer)
        {

            //read Image List XML file
            if (File.Exists(ImageXMLFilePathInServer))
            {
                StreamReader objStreamReader = File.OpenText(ImageXMLFilePathInServer);
                string ImageListXMLContent = objStreamReader.ReadToEnd();
                objStreamReader.Close();

                return ImageListXMLContent;
            }
            else
            {
                return Null.NullString;
            }

        }

        private void BindConfig()
        {
            //If this is the first time to the page, bind the config data to the text box
            FlashImageRotatorInfo objFlashImageRotatorInfo = new FlashImageRotatorInfo();
            FlashImageRotatorController objFlashImageContoller = new FlashImageRotatorController();

            objFlashImageRotatorInfo = objFlashImageContoller.GetFlashImageRotator(ModuleId);

            if (objFlashImageRotatorInfo != null)
            {
                _isNew = false;

                //The Basics:
                if (objFlashImageRotatorInfo.Height != Null.NullInteger)
                {
                    txtHeight.Text = objFlashImageRotatorInfo.Height.ToString();
                }

                if (objFlashImageRotatorInfo.Width != Null.NullInteger)
                {
                    txtWidth.Text = objFlashImageRotatorInfo.Width.ToString();
                }

                if (objFlashImageRotatorInfo.File.Trim() != Null.NullString)
                {
                    ddlImageListXMLFile.Items.FindByValue(objFlashImageRotatorInfo.File.Trim()).Selected = true;

                    strImageXMLFilePathInServer = strImageXMLFolderPathInServer + objFlashImageRotatorInfo.File;
                    txtImageListXML.Text = LoadImgeListXMLFile(strImageXMLFilePathInServer);

                }
                else
                {
                    //If the first time visit the setting page, use the default ImageList.xml
                    ddlImageListXMLFile.Items.FindByValue("ImageList.xml").Selected = true;
                    txtImageListXML.Text = LoadImgeListXMLFile(strImageXMLFilePathInServer);
                }
                if (objFlashImageRotatorInfo.Transtion.Trim() != Null.NullString)
                {
                    droplistTranstion.ClearSelection();
                    droplistTranstion.Items.FindByValue(objFlashImageRotatorInfo.Transtion.Trim()).Selected = true;
                }

                //The Colors:
                if (objFlashImageRotatorInfo.BackColor.Trim() != Null.NullString)
                {
                    cpicBackColor.Color = objFlashImageRotatorInfo.BackColor.Trim();
                }
                else
                {
                    cpicScreenColor.Color = String.Empty;
                }

                if (objFlashImageRotatorInfo.FrontColor.Trim() != Null.NullString)
                {
                    cpicFrontColor.Color = objFlashImageRotatorInfo.FrontColor.Trim();
                }
                else
                {
                    cpicFrontColor.Color = String.Empty;
                }

                if (objFlashImageRotatorInfo.LightColor.Trim() != Null.NullString)
                {
                    cpicLightColor.Color = objFlashImageRotatorInfo.LightColor.Trim();
                }
                else
                {
                    cpicLightColor.Color = String.Empty;
                }

                if (objFlashImageRotatorInfo.ScreenColor.Trim() != Null.NullString)
                {
                    cpicScreenColor.Color = objFlashImageRotatorInfo.ScreenColor.Trim();
                }
                else
                {
                    cpicScreenColor.Color = String.Empty;
                }

                //Display Appearance:

                urlctlLogo.Url = objFlashImageRotatorInfo.Logo;
                if (objFlashImageRotatorInfo.OverStrech.Trim() != Null.NullString)
                {
                    droplistOverStretch.ClearSelection();
                    droplistOverStretch.Items.FindByValue(objFlashImageRotatorInfo.OverStrech.Trim()).Selected = true;
                }

                droplistShowIcon.ClearSelection();
                droplistShowIcon.Items.FindByValue(objFlashImageRotatorInfo.ShowIcons.ToString().ToLower()).Selected = true;

                droplistShowEq.ClearSelection();
                droplistShowEq.Items.FindByValue(objFlashImageRotatorInfo.ShowEq.ToString().ToLower()).Selected = true;

                //Controlbar Appearance:
                droplistShowNavigation.ClearSelection();
                droplistShowNavigation.Items.FindByValue(objFlashImageRotatorInfo.ShowNavigation.ToString().ToLower()).Selected = true;

                //Playback Behaviour:
                urlctlAudio.Url = objFlashImageRotatorInfo.Audio;


                droplistAutoStart.ClearSelection();
                droplistAutoStart.Items.FindByValue(objFlashImageRotatorInfo.AutoStart.ToString().ToLower()).Selected = true;

                if (objFlashImageRotatorInfo.Repeat.Trim() != Null.NullString)
                {
                    droplistRepeat.ClearSelection();
                    droplistRepeat.Items.FindByValue(objFlashImageRotatorInfo.Repeat.Trim().ToLower()).Selected = true;
                }

                if (objFlashImageRotatorInfo.RotateTime != Null.NullInteger)
                {
                    txtRotateTime.Text = objFlashImageRotatorInfo.RotateTime.ToString();
                }

                droplistShuffle.ClearSelection();
                droplistShuffle.Items.FindByValue(objFlashImageRotatorInfo.Shuffle.ToString().ToLower()).Selected = true;

                if (objFlashImageRotatorInfo.Volume != Null.NullInteger)
                {
                    txtVolume.Text = objFlashImageRotatorInfo.Volume.ToString();
                }

                //External Commnunication:
                droplistEnableJs.ClearSelection();
                droplistEnableJs.Items.FindByValue(objFlashImageRotatorInfo.EnableJS.ToString().ToLower()).Selected = true;

                if (objFlashImageRotatorInfo.JavascriptID.Trim() != Null.NullString)
                {
                    txtJavascriptID.Text = objFlashImageRotatorInfo.JavascriptID.Trim();
                }
                else
                {
                    txtJavascriptID.Text = String.Empty;
                }

                droplistLinkFromDisplay.ClearSelection();
                droplistLinkFromDisplay.Items.FindByValue(objFlashImageRotatorInfo.LinkFromDisplay.ToString().ToLower()).Selected = true;

                if (objFlashImageRotatorInfo.LinkTarget.Trim() != Null.NullString)
                {
                    txtLinkTarget.Text = objFlashImageRotatorInfo.LinkTarget.Trim();
                }
                else
                {
                    txtLinkTarget.Text = String.Empty;
                }

            }
            else
            {

                _isNew = true;
            }

            ViewState["IsNew"] = _isNew;
        }

        #endregion



    }
}
